package cn.sc.summer.core.wrapper;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.sc.summer.exception.util.HttpHelper;
import cn.sc.summer.exception.wrapper.BaseHttpServletRequestWrapper;
import cn.sc.summer.token.service.EncryptService;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;

public class DecryptRequestWrapper extends BaseHttpServletRequestWrapper {

    public DecryptRequestWrapper(HttpServletRequest request,
                                 EncryptService encryptService) {
        super(request);
        String bodyString = HttpHelper.getBodyString(request);
        super.NEW_BODY = StringEscapeUtils.unescapeJava(encryptService.decrypt(request, bodyString));
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (CharSequenceUtil.isBlank(value)) {
            return value;
        }
        return HtmlUtils.htmlEscape(value);
    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if (CharSequenceUtil.isBlank(value)) {
            return value;
        }
        return HtmlUtils.htmlEscape(value);
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (ObjectUtil.isNotNull(values)) {
            for (int i = 0; i < values.length; i++) {
                values[i] = HtmlUtils.htmlEscape(values[i]);
            }
        }
        return values;
    }

}
